# Backend Dockerfile for FastAPI application
# 多阶段构建以减小镜像体积
FROM python:3.13-slim as builder

ADD debian.sources /etc/apt/sources.list.d/debian.sources

# 设置工作目录
WORKDIR /app

# 安装构建依赖
RUN apt-get update && apt-get install -y \
    gcc \
    postgresql-client \
    && rm -rf /var/lib/apt/lists/*

# 复制依赖文件
COPY requirements.txt .

RUN pip config set global.index-url https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple

RUN python -m pip install --upgrade pip

# 安装 Python 依赖到用户目录
RUN pip install some-package --user --no-cache-dir -r requirements.txt

# 生产阶段
FROM python:3.13-slim

# 设置工作目录
WORKDIR /app

# 安装运行时依赖
RUN apt-get update && apt-get install -y \
    postgresql-client \
    && rm -rf /var/lib/apt/lists/*

# 从构建阶段复制依赖
COPY --from=builder /root/.local /root/.local

# 设置 PATH
ENV PATH=/root/.local/bin:$PATH

# 复制应用代码
COPY . .

# 复制启动脚本并设置权限
RUN chmod +x start.sh

# 暴露端口
EXPOSE 8000

# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD python -c "import requests; requests.get('http://localhost:8000/docs')" || exit 1

# 运行应用（生产环境不使用 --reload）
CMD ["./start.sh"]
